﻿using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Common.Logging;
using Quartz;
using HCCapture;
using System.Collections.Generic;
using DHNetSDK;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;

namespace DHCapture.Job
{
    public class DHCaptureJob : IJob
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(DHCaptureJob));

        public static bool IsLoginAll = false;

        public static List<DHCammera> ActiveCammerList = new List<DHCammera>();

        public void Execute(IJobExecutionContext context)
        {
            try
            {
                //等待登录成功
                if (!IsLoginAll)
                {
                    logger.Info("wait for all login success...");
                    while (!IsLoginAll)
                    {
                        Thread.Sleep(500);
                    }
                    logger.Info("all login success begin execute job...");
                }

                ReLoginALL();
                DHCaptureJob.SnapPictureAll();
            }
            catch (Exception ex)
            {
                logger.Fatal(ex.Message);
            }
        }

        /// <summary>
        /// 初始化SDK
        /// </summary>
        public static void DHInitSDK()
        {
            var m_bInit = DHClient.DHInit((lLoginID, pchDVRIP, nDVRPort, dwUser) =>
            {
                //查找 CammerList 把 lLoginID置为0

                //设备断开重新登录
                int idx = ActiveCammerList.FindIndex(c => c.lLoginID.Equals(lLoginID));
                if (idx > 0)
                {
                    ActiveCammerList[idx].lLoginID = -1;
                }
            }, IntPtr.Zero);

            if (!m_bInit)
            {
                logger.Error("初始化失败");
            }
            else
            {
                //图片接受回调
                DHClient.DHSetSnapRevCallBack((lLoginID, pBuf, RevLen, EncodeType, CmdSerial, dwUser) =>
                {
                    //通过loginID 查找index
                    //int idx = m_nLoginIDList.FindIndex(t => t.Equals(lLoginID));

                    var c = ActiveCammerList.Find(t => t.lLoginID.Equals(lLoginID));
                    if (RevLen == 0 && c != null)
                    {
                        c.lLoginID = -1;
                        return;
                    }

                    byte[] buf = new byte[RevLen];
                    Marshal.Copy(pBuf, buf, 0, (int)RevLen);

                    switch (DevConfig.Mode)
                    {
                        case SaveMode.仅本地:
                            c.SaveLocal(buf, RevLen);
                            break;
                        case SaveMode.仅FTP:
                            c.SaveFtp(buf, RevLen);
                            break;
                        case SaveMode.本地和FTP:
                            c.SaveLocal(buf, RevLen);
                            c.SaveFtp(buf, RevLen);
                            break;
                        default:
                            c.SaveLocal(buf, RevLen);
                            break;
                    }

                }, 0);
            }
        }

        /// <summary>
        /// 清空SDK
        /// </summary>
        public static void DHCleanup()
        {
            DHClient.DHCleanup();
        }

        public static void ReLoginALL()
        {
            var logOutList = DHCaptureJob.ActiveCammerList.Where(c => c.lLoginID <= 0).ToList();
            if (logOutList.Count == 0) return;

            logOutList.ForEach(async c =>
            {
                if (c.lLoginID <= 0)
                {
                    await c.LogInAsync();
                }
            });
        }

        public async static Task LoginALLAsync()
        {
            DevConfig.LoadConfig();

            var CammeraList = new List<DHCammera>();

            foreach (var d in DevConfig.devList)
            {
                var dhCammera = new DHCammera()
                {
                    DvInfo = d,
                    CapJpgPath = DevConfig.CapJpgPath
                };
                dhCammera.Initialize();
                CammeraList.Add(dhCammera);
            }

            logger.Info("begin all login...");

            foreach (var c in CammeraList)
            {
                //var msg = "";
                await c.LogInAsync();
                //c.LogIn(ref msg);
            }

            logger.Info("end all login...");

            DHCaptureJob.IsLoginAll = true;

            var query = from c in CammeraList
                        where c.Active
                        select c;

            DHCaptureJob.ActiveCammerList = query.ToList();
            logger.Info("find active cammer list...");
        }

        /// <summary>
        /// 抓取所有图片
        /// </summary>
        private static void SnapPictureAll()
        {
            logger.Info("begin capture foreach...");
            foreach (var c in ActiveCammerList)
            {
                if (c.DvInfo.PresetIndex > 0)
                {
                    c.DHPTZControl(c.DvInfo.PresetIndex);
                    Thread.Sleep(3000);
                }
                //--模式 0 本地，1 ftp，2 本地和ftp
                c.SnapPictureAsync();

                if (c.DvInfo.PrePresetIndex > 0)
                {
                    c.DHPTZControl(c.DvInfo.PrePresetIndex);
                }
            }
            logger.Info("end capture foreach..");
        }


        /// <summary>
        /// 释放资源
        /// </summary>
        public static void DisposeAll()
        {
            logger.Info("begin dispose all...");
            ActiveCammerList.ForEach(d =>
            {
                d.LogOut();
                DHCaptureJob.DHCleanup();
            });
            logger.Info("end dispose all...");
        }

    }

}
